import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入子组件
import Login from '@/views/login/index.vue'
import Layout from '@/views/layout/index.vue'
import Chart from '@/views/chart/index.vue'
import User from '@/views/user/index.vue'
import Question from '@/views/question/index.vue'
import Enterprise from '@/views/enterprise/index.vue'
import Subject from '@/views/subject/index.vue'

import { getToken } from '@/utils/token'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login, meta: { needAuth: false } },
    {
      path: '/layout',
      component: Layout,
      children: [
        { path: 'chart', component: Chart },
        { path: 'user', component: User },
        { path: 'question', component: Question },
        { path: 'enterprise', component: Enterprise },
        { path: 'subject', component: Subject }
      ]
    }
  ]
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(
  location: any,
  onResolve: any,
  onReject: any
) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return (originalPush.call(this, location) as any).catch((err: any) => err)
}

router.beforeEach((to, from, next) => {
  if (to.meta.needAuth === false) {
    next()
  } else {
    // 需要先判断是否登录了
    if (!getToken()) {
      // 未登录
      router.push('/login')
    } else {
      next()
    }
  }
})

export default router
